package com.xujie.application.weather.scheduler;

import com.xujie.domain.service.WeatherStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

@Slf4j
@Component
public class WeatherStatsScheduler {

  @Autowired
  private WeatherStatsService weatherStatsService;

  // 支持的城市列表
  private static final List<String> SUPPORTED_CITIES = Arrays.asList("成都");

  /**
   * 每分钟执行一次，统计未来7天的天气数据
   */
  @Scheduled(cron = "0 * * * * ?")
  public void minutelyFutureWeatherStats() {
    log.info("开始执行未来7天天气统计任务");

    try {
      // 获取当前时间
      Calendar calendar = Calendar.getInstance();
      Date now = calendar.getTime();

      // 为每个支持的城市执行统计
      for (String city : SUPPORTED_CITIES) {
        try {
          log.info("开始统计{}的未来7天天气数据", city);

          // 统计未来7天的数据
          for (int i = 0; i < 7; i++) {
            calendar.setTime(now);
            calendar.add(Calendar.DAY_OF_MONTH, i);
            Date targetDate = calendar.getTime();

            try {
              weatherStatsService.calculateAndSaveStats(city, targetDate);
              log.debug("完成{}在{}的天气数据统计", city, targetDate);
            } catch (Exception e) {
              log.error("统计{}在{}的天气数据失败: {}", city, targetDate, e.getMessage());
            }
          }

          log.info("完成{}的未来7天天气数据统计", city);
        } catch (Exception e) {
          log.error("统计{}的未来7天天气数据失败: {}", city, e.getMessage());
        }
      }

      log.info("未来7天天气统计任务执行完成");
    } catch (Exception e) {
      log.error("执行未来7天天气统计任务失败", e);
    }
  }
}